package com.cskaoyan.transfer;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 创建日期: 2022/03/22 15:56
 *
 * @author ciggar
 *
 * 转账案例
 */
public class TransferDemo {


    // 风华哥给长风发工资 1000

    // 1. 给风华哥的账户-1000

    // 2. 给长风的账户 + 1000

    public static void main(String[] args) throws SQLException {

        transfer("风华哥","长风",1000);

    }



    // 转账
    public static void transfer(String fromName,String toName, int money) throws SQLException {

        Connection connection = JDBCUtils.getConnection();

        PreparedStatement preparedStatement = null;
        PreparedStatement preparedStatement2 = null;

        // 开启事务
        connection.setAutoCommit(false);

        try {
            // 给风华哥的账户扣钱
            preparedStatement = connection.prepareStatement("update account set money = money - ? where name = ?");

            preparedStatement.setInt(1, money);
            preparedStatement.setString(2, fromName);

            int affectedRows = preparedStatement.executeUpdate();

            if (affectedRows > 0) {

                System.out.println("扣钱成功！！！");

            } else {

                return;

            }

            int i = 1 / 0;

            // 给长风的账户加钱
            preparedStatement2 = connection.prepareStatement("update account set money = money + ? where name = ?");

            preparedStatement2.setInt(1, money);
            preparedStatement2.setString(2, toName);

            int affectedRows2 = preparedStatement2.executeUpdate();

            if (affectedRows2 > 0) {
                System.out.println("加钱成功！！！");
                connection.commit();
            }else {
                connection.rollback();
            }

        }catch (Exception ex) {

            // 回滚事务
            connection.rollback();

            System.out.println("回滚成功！！！");
        }


        // 关闭资源
        preparedStatement.close();
        preparedStatement2.close();
        JDBCUtils.close(null,null,connection);


    }


}
